/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */
import {expect} from '@jest/globals';
import {iconv} from '@ohos/hvigor';
import fse from 'fs-extra';
import path from 'path';
import {runHvigorAsync} from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import {TestCaseBuilder} from '../../plugins/task-builder/task-case-builder';
import {ProjectBuildOption, TestCaseFun} from '../../plugins/task-builder/test-case';
import {TestTaskOptionBuilder} from '../../plugins/task-builder/test-task-option';
import * as compressing from 'compressing';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const moduleFile = await fse.readFile(`${projectRootPath}/build-profile.json5`);
  const entryPath = project.getModule('entry').moduleRootPath();
  // 去掉文件中多余的 ,
  const str = iconv.decode(moduleFile, 'utf-8').replace(/(,[\r\n]\s+[}|\]])/g, ($1) => $1.slice(1));
  const moduleObj = JSON.parse(str);

  moduleObj.app.products[0].versionCode = 111111;
  await fse.writeFile(`${projectRootPath}/build-profile.json5`, JSON.stringify(moduleObj, null, 2), 'utf-8');
  // 执行hap构建
  const commonCommand = '--mode module -p product=default assembleHap --analyze=normal --parallel --incremental --daemon'.split(' ');
  const result = await runHvigorAsync(project.projectRootPath(), commonCommand);
  record.addStep('第一次全量构建，直接构建成功', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  // 直接进行增量构建
  const resultIncre = await runHvigorAsync(project.projectRootPath(), commonCommand);
  record.addStep('不修改进行增量构建，GeneratePkgModuleJson任务应该为UP-TO-DATE', resultIncre);
  expect(resultIncre.stdout).toContain('UP-TO-DATE :entry:default@GeneratePkgModuleJson');

  moduleObj.app.products[0].versionCode = 222222;
  await fse.writeFile(`${projectRootPath}/build-profile.json5`, JSON.stringify(moduleObj, null, 2), 'utf-8');
  // 再次构建
  const resultChangeIncre = await runHvigorAsync(project.projectRootPath(), commonCommand);
  record.addStep('修改versionCode后再次增量构建，GeneratePkgModuleJson应该为Finished，且产物module.json进行了更新', resultChangeIncre);
  expect(resultChangeIncre.stdout).toContain('Finished :entry:default@GeneratePkgModuleJson');
  const outDir = await parse(path.resolve(entryPath, 'build/default/outputs/default/entry-default-unsigned.hap'))
  const moduleJsonFile = await fse.readFile(`${outDir}/module.json`);
  const strModuleJson = iconv.decode(moduleJsonFile, 'utf-8').replace(/(,[\r\n]\s+[}|\]])/g, ($1) => $1.slice(1));
  const moduleJsonObj = JSON.parse(strModuleJson);
  expect(moduleJsonObj.app.versionCode === 222222).toEqual(true);
}


/**
 * 解析产物包
 * @param {string} hqfPath 产物包的绝对路径
 * @returns {Promise<string>} 解析的产物目录
 */
async function parse(hqfPath: string) {
  const dir = path.dirname(hqfPath);
  let fileName = path.basename(hqfPath);
  fileName = fileName.replace(fileName.slice(fileName.lastIndexOf('.')), '.zip');
  const zipPath = path.resolve(dir, fileName);

  // 将生成的xxx包复制为zip包
  fse.copyFileSync(hqfPath, zipPath);
  // 解压zip，解析出生成hap里的内容
  const outputDir = zipPath.slice(0, -4);
  await compressing.zip.uncompress(zipPath, outputDir);
  return outputDir;
}

TestCaseBuilder.builder()
  .caseName('GENERATE-PKG-MODULE-JSON-E2E')
  .description('GeneratePkgModuleJson任务的e2e用例')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).build())
  .testFun(testfun)
  .load();
